/*  
 Copyright 2010 The 'Tribe.Blog' development team  
 (http://tribecache.codeplex.com/team/view)

 This library is licensed under the Ms-PL Microsoft Public License.  You should 
 have received a copy of the license along with the source code.  If not, an online copy
 of the license can be found at http://tribecache.codeplex.com/license.
*/

using System;
using Tribe.Cache.Service;

namespace Tribe.Cache.Factory
{
    ///<summary>
    /// Factory that creates the cache expiration service
    ///</summary>
    public class CacheExpirationServiceFactory : ICacheExpirationServiceFactory
    {
        /// <summary>
        /// private field - ICacheFactory (needed so the cache expiration service has exposure to the cache table)
        /// </summary>
        private readonly ICacheFactory _cacheFactory;

        /// <summary>
        /// Instance of the CacheExpirationService
        /// </summary>
        private static volatile CacheExpirationService _cacheExpirationService;
        private static readonly object CacheExpirationServiceSyncRoot = new Object();

        ///<summary>
        /// Default constructor
        ///</summary>
        public CacheExpirationServiceFactory()
        {
            throw new InvalidOperationException(Resources.Resources.CacheExpirationServiceDoNotCallDefaultContructor);
        }

        ///<summary>
        /// Overloaded constructor - Will take an instance of the ICacheFactory
        ///</summary>
        ///<param name="cacheFactory">Used create or get the singleton instance of the cache table</param>
        public CacheExpirationServiceFactory(ICacheFactory cacheFactory)
        {
            _cacheFactory = cacheFactory;
        }

        /// <summary>
        /// Used create a singleton instance of the cache expiration service
        /// </summary>
        ///<param name="invocationSchedule">The time period between invocations of the cache expiration service cleanup task</param>
        public void CreateCacheExpirationService(TimeSpan invocationSchedule)
        {
            if (_cacheExpirationService == null)
            {
                lock (CacheExpirationServiceSyncRoot)
                {
                    if (_cacheExpirationService == null)
                        _cacheExpirationService = new CacheExpirationService();
                }
            }
            _cacheFactory.CreateCache();
            _cacheExpirationService.Start(_cacheFactory, invocationSchedule);
        }
        ///<summary>
        /// Removes the instance of the running cache expiration service
        ///</summary>
        public void Dispose()
        {
            _cacheExpirationService.Dispose();
        }
    }
}